package TP;

import fr.inria.acacia.corese.api.IDatatype;
import fr.inria.acacia.corese.exceptions.EngineException;
import fr.inria.edelweiss.kgram.core.Mapping;
import fr.inria.edelweiss.kgram.core.Mappings;
import fr.inria.edelweiss.kgraph.core.Graph;
import fr.inria.edelweiss.kgraph.query.QueryProcess;
import fr.inria.edelweiss.kgraph.rule.RuleEngine;
import fr.inria.edelweiss.kgtool.load.Load;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.JSONArray;
import org.json.JSONObject;

@WebServlet(name = "Search", urlPatterns = {"/search"})
public class Search extends HttpServlet {

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, EngineException, URISyntaxException {
        response.setContentType("text/html;charset=UTF-8");
        try (PrintWriter out = response.getWriter()) {

//        String dbpedia_service = "<http://dbpedia.org/sparql>";
            ServletContext context = getServletConfig().getServletContext();
            Graph graph = Server.getGraph(context);
            String genre = request.getParameter("genre");
            QueryProcess exec = QueryProcess.create(graph);
            String query = "prefix geo: <http://www.w3.org/2003/01/geo/wgs84_pos#> "
                    + "prefix e: <http://example.com/> "
                    + "select ?label ?long ?lat ?description ?image where"
                    + "{ <" + genre + "> geo:location ?location;"
                    + "                  rdfs:label ?label."
                    + "?location geo:long ?long;"
                    + "          geo:lat  ?lat."
                    + "  OPTIONAL { <" + genre + "> e:description ?description. }"
                    //+ "  OPTIONAL { <" + genre + "> e:image ?image. }"
                    + "  FILTER( lang(?label) = 'fr' )"
                    + "}";

            Logger.getLogger(IndexServlet.class.getName()).log(Level.WARNING, query);
            JSONArray jsonarray = new JSONArray();
            JSONObject jsonData = new JSONObject();
            Mappings map = exec.query(query);
            List<Genre> genres = new ArrayList();

            Logger.getLogger(IndexServlet.class.getName()).log(Level.WARNING, "Nombre match " + map.size());

            for (Mapping m : map) {
                IDatatype label = (IDatatype) m.getValue("?label");
                IDatatype lon = (IDatatype) m.getValue("?long");
                IDatatype lat = (IDatatype) m.getValue("?lat");
                IDatatype image = (IDatatype) m.getValue("?image");
                IDatatype description = (IDatatype) m.getValue("?description");

                Genre g = new Genre(
                        null == label ? "" : label.getLabel(),
                        null == description ? "" : description.getLabel(),
                        null == lon ? "" : lon.getLabel(),
                        null == lat ? "" : lat.getLabel()
                );
                genres.add(g);

                jsonarray.put(g.toJson());

                // Logger.getLogger(IndexServlet.class.getName()).log(Level.WARNING, context.getRealPath("/Data.json"));
            }
            String JsonFile = context.getRealPath("/Data.json");
            Logger.getLogger(IndexServlet.class.getName()).log(Level.WARNING, context.getRealPath("/Data.json"));
            FileWriter fw = new FileWriter(JsonFile, false);
            BufferedWriter output = new BufferedWriter(fw);
            output.write(jsonarray.toString().replace("\\", ""));
            output.flush();

            request.setAttribute("genres", jsonarray.toString());
            request.getRequestDispatcher("search.jsp").forward(request, response);
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);

        } catch (EngineException | URISyntaxException ex) {
            Logger.getLogger(Search.class
                    .getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (EngineException | URISyntaxException ex) {
            Logger.getLogger(Search.class
                    .getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
